package servlet;

import all.user;
import all.JdbcUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
//@WebServlet(urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        // 获取请求中键名为 u 的值
        String username = req.getParameter("u");
        // 获取请求中键名为 p 的值
        String password = req.getParameter("p");
        // 获取请求中键名为 c 的值
        String code = req.getParameter("c");
        System.out.println(username+password);
        PrintWriter writer = resp.getWriter();
        HttpSession session = req.getSession();
        Object c = session.getAttribute("C");
        boolean isTrue = c!=null&&code!=null&&code.equals(c);
        if(!isTrue){
            resp.sendRedirect("/hkp/login.jsp");
            return;
        }

        String sql = "SELECT id FROM `user` WHERE username=? AND password=md5(?)";
//        user user = JdbcUtils.select(sql, user.class,username,password);
        Long id = JdbcUtils.select(sql, Long.class, username, password);
        if (id!=null){
            session.setAttribute("UID",id);
//            writer.write("登陆成功");
            resp.sendRedirect("/hkp/");
        }else{
            resp.sendRedirect("/hkp/login.jsp");
        }
//        String message = id != null ? "登录成功！" : "登录失败！";
//        resp.setContentType("text/html;charset=utf-8");
//        PrintWriter writer = resp.getWriter();
//        writer.write(message);
        writer.flush();
        writer.close();


    }
}
